<template>
  <div class="mall-page">
    <h1>商城系统</h1>
    <ul>
      <li v-for="product in currentProducts" :key="product.id">
        {{ product.name }} - {{ product.price }} 元
      </li>
    </ul>
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>{{ currentPage }} / {{ totalPages }}</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import api from '@/api/index.js'

const products = ref([])
const currentPage = ref(1)
const itemsPerPage = ref(5)

onMounted(async () => {
  try {
    const response = await api.get('/products')
    products.value = response.data
  } catch (error) {
    console.error('获取商品列表失败:', error)
  }
})

const totalPages = computed(() => {
  return Math.ceil(products.value.length / itemsPerPage.value)
})

const currentProducts = computed(() => {
  const startIndex = (currentPage.value - 1) * itemsPerPage.value
  const endIndex = startIndex + itemsPerPage.value
  return products.value.slice(startIndex, endIndex)
})

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}
</script>

<style scoped>
.mall-page {
  padding: 20px;
}

.pagination {
  margin-top: 20px;
}

.pagination button {
  margin: 0 5px;
}
</style>